<template>
  <div
    :id="id"
    :style="{ width: width + 'px', height: height + 'px' }"
    :class="className"
  ></div>
</template>

<script lang="ts">
import {
  defineComponent,
  onBeforeUnmount,
  onMounted,
  PropType,
  toRefs,
  watch,
} from "vue";
import { EChartsType, getInstanceByDom, init } from "echarts";
export default defineComponent({
  name: "Chart",
  props: {
    id: {
      type: String,
      required: true,
      default: "echartsId",
    },
    width: {
      type: Number,
      required: false,
      default: 200,
    },
    height: {
      type: Number,
      required: false,
      default: 200,
    },
    className: {
      type: String,
      required: false,
    },
    config: {
      type: Object as PropType<any>,
    },
  },
  setup(props) {
    const { id, config } = toRefs(props);
    let chartInstance: EChartsType | null = null;
    const renderChart = () => {
      const renderedInstance = getInstanceByDom(
        document.getElementById(id.value) as HTMLElement
      );
      if (renderedInstance) {
        chartInstance = renderedInstance;
      } else {
        chartInstance = init(document.getElementById(id.value) as HTMLElement);
      }
      chartInstance.setOption(config?.value as any);
    };

    watch(
      () => config?.value,
      () => {
        renderChart();
      },
      {
        deep: true,
      }
    );

    onMounted(() => {
      renderChart();
      window.addEventListener("resize", () => chartInstance?.resize());
    });

    onBeforeUnmount(() => {
      chartInstance && chartInstance.dispose();
    });
  },
});
</script>

